import React, { useState } from 'react';
import { Form, Select, Modal, Input } from 'antd';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import Icon from './../../icon/Icon';

const screenIcon: React.CSSProperties = {
  position: 'absolute',
  right: 0,
  top: '20px'
};

const importDefaultScriptText = `
importXlsx(function (res) {
  // 去除第一行的文字行
  var data = res.filter(function(item,index){
    return index !== 0
  })   
  // 填写url
  var url = '/bk/mid/shell/postInventoryGenEntries'

  showLoading();

  server({
      url:url ,
      // 上传数据的格式 
      data:{
        data:data
      },
  }, function (res) {
      hideLoading();   
      if(res.data && res.data.status =='200'){
        var result = res.data.result;
        console.log(result)
        success('导入成功')
        _REFS_[0].onListRefresh()
      } else{
        error("导入失败");
      }
  })
 
})
`;
const exportDefaultScriptText = `
exportXlsx({
  columns:_REFS_[0].getColumns(), dataSource:[], fileName:'模板.xlsx'
  })
`;


// 

const exportDataDefaultScriptText = `
// eg:
//  attributes要按照前端展示的顺序来
// mapping里传入需要映射的字段，以及字段内容对应的中文

// where: {},
// attributes: [
// "purOrderNumber",
// "orderStatus",
// ],
// mapping: {
// orderStatus: {
// "10": "未提交",
// "20": "进行中"
// }

var columns = _REFS_[0].getColumns(); //默认列
var tableName = 'tableName';   // 文件名
var moduleName = 'purchase/PurOrderHead/find'; // 格式:模块名/模型名/find

//过滤action和表单字段
var attributes = columns.filter(function(item,index){
  return item.dataIndex !== 'action' && item.dataIndex.indexOf('.') < 0
})

attributes = attributes.map(function(item){
return item.dataIndex
});

_REFS_[0].openExportDialog({
  initialValues:{
    tableName: tableName,
    fileType: 'Excel',
    exportDataType: 'all',
    maxExportLines: 3000,
  },
  moduleName:moduleName,
  query:{
    // where:{},
    attributes:attributes
    // mapping:{}
  }
  })
`;

const FormItem = Form.Item;
const Option = Select.Option;
const extensions = [javascript({ jsx: true })];

const typeOptions = ['primary', 'ghost', 'dashed', 'link', 'text', 'default'];
const classTypeOptions = [
  {
    value: 'default',
    label: '普通按钮'
  },
  {
    value: 'import',
    label: '导入按钮'
  },
  {
    value: 'export',
    label: '导出模板'
  },
  {
    value: 'exportData',
    label: '导出数据'
  }
];

const ButtonController = ({ initialValue, onChange, tabSource }: { onChange: (v: object) => void; initialValue: any; tabSource?: any[]; }) => {

  const [visible, setVisible] = useState(false);
  const [codeMirrorValue, setCodeMirrorValue] = useState('');

  function show() {
    setVisible(true);
    setCodeMirrorValue(initialValue?.scriptText || '');
  }

  function onOk() {
    setVisible(false);
    onChange({ scriptText: codeMirrorValue });
    setCodeMirrorValue('');
  }

  return (
    <Form labelCol={{ span: 4 }}>
      <FormItem label='风格'>
        <Select
          value={initialValue?.type || 'default'}
          onChange={e => {
            onChange({ type: e });
          }}>
          {typeOptions.map(item => (
            <Option key={item} value={item}>{item}</Option>
          ))}
        </Select>
      </FormItem>

      <FormItem label='类型'>
        <Select
          value={initialValue?.classType || 'default'}
          onChange={e => {
            if (e === 'import') {
              onChange({ classType: e, text: '导入数据', textEn: 'Import Data', scriptText: importDefaultScriptText });
            } else if (e === 'export') {
              onChange({ classType: e, text: '下载导入模板', textEn: 'Download Import Template', scriptText: exportDefaultScriptText });
            } else if (e === 'exportData') {
              onChange({ classType: e, text: '导出数据', textEn: 'Export Data', scriptText: exportDataDefaultScriptText });
            } else {
              onChange({ classType: e });
            }
          }}>
          {classTypeOptions.map(item => (
            <Option key={item.value} value={item.value}>{item.label}</Option>
          ))}
        </Select>
      </FormItem>

      <FormItem label='文字'>
        <Input
          value={initialValue?.text}
          onChange={e => {
            onChange({ text: e.target.value });
          }} />
      </FormItem>

      <FormItem label='文字(EN)'>
        <Input
          value={initialValue?.textEn}
          onChange={e => {
            onChange({ textEn: e.target.value });
          }} />
      </FormItem>
      
      <FormItem label='文字颜色'>
        <Input
          placeholder='文字色值，如#FFF'
          value={initialValue?.color}
          onChange={e => {
            onChange({ color: e.target.value });
          }} />
      </FormItem>

      <FormItem label='背景色'>
        <Input
          placeholder='背景色值，如#000'
          value={initialValue?.background}
          onChange={e => {
            onChange({ background: e.target.value });
          }} />
      </FormItem>

      {
        tabSource && <FormItem label='tab下隐藏'>
          <Select
            mode="multiple"
            allowClear
            value={initialValue?.tabIds || []}
            onChange={e => {
              onChange({ tabIds: e });
            }}>
            {tabSource.map(item => (
              <Option key={item.id} value={item.value}>{item.lable}</Option>
            ))}
          </Select>
        </FormItem>
      }
      <div style={{ position: 'relative' }}>
        <FormItem label='脚本内容'>
          <CodeMirror
            value={initialValue?.scriptText}
            onChange={(e: string) => {
              onChange({ scriptText: e });
            }} />
        </FormItem>
        <Icon
          style={screenIcon}
          icon='&#xe67c;'
          onClick={show} />
      </div>
      <Modal
        visible={visible}
        title='脚本'
        width={1000}
        onCancel={() => setVisible(false)}
        onOk={onOk}>
        <CodeMirror
          extensions={extensions}
          onChange={setCodeMirrorValue}
          value={codeMirrorValue} />
      </Modal>
    </Form>
  );
};

export default ButtonController;